package com.andova.lifecycle;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.view.LayoutInflater;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.collection.ArrayMap;
import androidx.core.view.LayoutInflaterCompat;

/**
 * Created by Administrator on 2018-03-20.
 *
 * @author kzaxil
 * @since 1.0.0
 */
public abstract class ActivityLifecycle implements Application.ActivityLifecycleCallbacks {
    private List<ILifecycle> mLifecycleList = new ArrayList<>(2);
    private Map<Activity, ActivityFactory2> mDelegateMap = new ArrayMap<>(2);

    private ActivityFactory2 getFactory2(Activity activity) {
        ActivityFactory2 factory2 = mDelegateMap.get(activity);
        if (factory2 == null) factory2 = new ActivityFactory2(activity, getDelegate(activity));
        mDelegateMap.put(activity, factory2);
        return factory2;
    }

    public void addLifecycleCallback(ILifecycle callback) {
        mLifecycleList.add(callback);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        for (ILifecycle callback : mLifecycleList) {
            callback.onActivityCreated(activity, getFactory2(activity).delegate());
        }
        LayoutInflater inflater = LayoutInflater.from(activity);
        try {
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(inflater, false);
            LayoutInflaterCompat.setFactory2(inflater, getFactory2(activity));
        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityStarted(Activity activity) {
        for (ILifecycle callback : mLifecycleList) {
            callback.onActivityStarted(activity, getFactory2(activity).delegate());
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        for (ILifecycle callback : mLifecycleList) {
            callback.onActivityDestroyed(activity);
        }
        mDelegateMap.remove(activity);
    }

    protected abstract List<IDelegate> getDelegate(Activity activity);
}
